<template>
  <div class="message-dialog-modal" @click.self="emit('close')">
    <div class="message-dialog-content">
      <!-- 对话头部 -->
      <div class="dialog-header">
        <button @click="emit('back')" class="back-btn">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
            <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
          </svg>
        </button>
        <div class="user-info">
          <div class="user-avatar-small">
            <img 
              v-if="targetUser.avatar" 
              :src="getAvatarUrl(targetUser.avatar)" 
              alt="头像"
            />
            <span v-else class="avatar-placeholder-small">
              {{ targetUser.nickname?.charAt(0) || 'U' }}
            </span>
          </div>
          <span class="user-name">{{ targetUser.nickname }}</span>
        </div>
        <button @click="emit('close')" class="close-btn">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
          </svg>
        </button>
      </div>

      <!-- 消息列表 -->
      <div class="dialog-body" ref="messageContainer">
        <div v-if="loading" class="loading">
          <svg viewBox="0 0 24 24" width="40" height="40" fill="currentColor" class="spin">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-3.31 0-6 2.69-6 6h2c0-2.21 1.79-4 4-4V6z"/>
          </svg>
        </div>

        <div v-else class="message-list">
          <div 
            v-for="msg in messages" 
            :key="msg.id"
            class="message-item"
            :class="{ sent: msg.isSent, received: !msg.isSent }"
          >
            <div class="message-avatar" v-if="!msg.isSent">
              <img 
                v-if="targetUser.avatar" 
                :src="getAvatarUrl(targetUser.avatar)" 
                alt="头像"
              />
              <span v-else class="avatar-placeholder-tiny">
                {{ targetUser.nickname?.charAt(0) || 'U' }}
              </span>
            </div>

            <div class="message-bubble">
              <div class="message-text">{{ msg.content }}</div>
              <div class="message-time">{{ formatTime(msg.createTime) }}</div>
            </div>

            <div class="message-avatar" v-if="msg.isSent">
              <img 
                v-if="currentUser.avatar" 
                :src="getAvatarUrl(currentUser.avatar)" 
                alt="头像"
              />
              <span v-else class="avatar-placeholder-tiny">
                {{ currentUser.nickname?.charAt(0) || 'U' }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入框 -->
      <div class="dialog-footer">
        <textarea 
          v-model="messageInput"
          placeholder="输入私信内容... (Enter 发送，Shift+Enter 换行)"
          rows="3"
          @keydown.enter.exact="handleEnterKey"
        ></textarea>
        <div class="footer-actions">
          <span class="char-count">{{ messageInput.length }}/500</span>
          <button 
            class="btn-send"
            :disabled="!messageInput.trim() || sending"
            @click="sendMessage"
          >
            {{ sending ? '发送中...' : '发送' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useUserStore } from '../stores/user'
import { getConversationDetail, markConversationRead } from '../api/message'
import { getAvatarUrl } from '../utils/url'
import { toast } from '../utils/toast'
import { wsManager } from '../utils/websocket'

const props = defineProps({
  targetUser: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['close', 'back'])

const userStore = useUserStore()
const currentUser = computed(() => userStore.userInfo)

const messages = ref([])
const messageInput = ref('')
const loading = ref(false)
const sending = ref(false)
const messageContainer = ref(null)

onMounted(() => {
  loadMessages()
  setupWebSocketListeners()
})

// 组件卸载时清理监听器
onUnmounted(() => {
  removeWebSocketListeners()
})

// 设置 WebSocket 消息监听
function setupWebSocketListeners() {
  // 监听新消息
  wsManager.on('newMessage', handleNewMessage)
  // 监听消息发送成功
  wsManager.on('messageSent', handleMessageSent)
}

// 移除 WebSocket 监听器
function removeWebSocketListeners() {
  wsManager.off('newMessage', handleNewMessage)
  wsManager.off('messageSent', handleMessageSent)
}

// 处理接收到的新消息
async function handleNewMessage(data) {
  // 只处理当前对话的消息
  if (data.senderId === props.targetUser.id) {
    messages.value.push({
      ...data,
      isSent: false
    })
    
    await nextTick()
    scrollToBottom()
    
    // 标记为已读
    await markConversationRead(props.targetUser.id)
  }
}

// 处理发送成功的消息（服务器确认）
function handleMessageSent(data) {
  // 可以在这里更新消息的状态，比如显示"已送达"
  console.log('消息发送成功确认:', data)
}

async function loadMessages() {
  loading.value = true
  try {
    // 使用正确的API调用方式 - 获取与特定用户的聊天记录
    const res = await getConversationDetail(props.targetUser.id, {
      page: 1,
      size: 50
    })
    if (res.code === 200) {
      // 处理消息列表，判断每条消息是否是当前用户发送的
      const messageList = res.data.list || []
      messages.value = messageList.map(msg => ({
        ...msg,
        isSent: msg.senderId === currentUser.value.id
      }))
      console.log('加载的消息列表:', messages.value)
      // 标记为已读
      await markConversationRead(props.targetUser.id)
    }
  } catch (error) {
    console.error('获取消息失败:', error)
    // 模拟数据
    messages.value = [
      {
        id: 1,
        content: '你好，我想请教一个数学问题...',
        createTime: new Date(Date.now() - 3600000).toISOString(),
        isSent: false
      },
      {
        id: 2,
        content: '你好，请说！',
        createTime: new Date(Date.now() - 3000000).toISOString(),
        isSent: true
      }
    ]
  } finally {
    loading.value = false
    scrollToBottom()
  }
}

function handleEnterKey(e) {
  // Enter 发送，Shift+Enter 换行
  e.preventDefault()
  sendMessage()
}

async function sendMessage() {
  if (!messageInput.value.trim() || sending.value) return
  
  if (messageInput.value.length > 500) {
    toast.warning('消息内容不能超过500字')
    return
  }

  sending.value = true
  const content = messageInput.value.trim()
  
  try {
    // 立即添加到消息列表（乐观更新）
    messages.value.push({
      id: Date.now(), // 临时ID，等服务器确认后会更新
      senderId: currentUser.value.id,
      receiverId: props.targetUser.id,
      content: content,
      createTime: new Date().toISOString(),
      isSent: true
    })
    
    messageInput.value = ''
    await nextTick()
    scrollToBottom()
    
    // 通过 WebSocket 发送消息（自动重连）
    const success = await wsManager.sendMessage(props.targetUser.id, content)
    
    if (!success) {
      // 发送失败，但消息已加入队列，会在重连后自动发送
      toast.info('正在重新连接...')
    }
  } catch (error) {
    console.error('发送失败:', error)
    toast.error('发送失败，请重试')
  } finally {
    sending.value = false
  }
}

function scrollToBottom() {
  if (messageContainer.value) {
    nextTick(() => {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    })
  }
}

function formatTime(timeStr) {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now - time

  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) {
    const hours = time.getHours().toString().padStart(2, '0')
    const minutes = time.getMinutes().toString().padStart(2, '0')
    return `${hours}:${minutes}`
  } else if (diff < 604800000) {
    return Math.floor(diff / 86400000) + '天前'
  } else {
    return time.toLocaleDateString()
  }
}
</script>

<style scoped lang="scss">
.message-dialog-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
  
  .message-dialog-content {
    width: 90%;
    max-width: 700px;
    height: 80vh;
    max-height: 700px;
    background: white;
    border-radius: 12px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .dialog-header {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 16px 20px;
      border-bottom: 1px solid #eee;
      background: #f6f8fa;
      
      .back-btn,
      .close-btn {
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: transparent;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        color: #57606a;
        transition: all 0.2s;
        flex-shrink: 0;
        
        &:hover {
          background: white;
          color: #24292f;
        }
      }
      
      .user-info {
        flex: 1;
        display: flex;
        align-items: center;
        gap: 10px;
        
        .user-avatar-small {
          width: 36px;
          height: 36px;
          
          img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
          }
          
          .avatar-placeholder-small {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            font-weight: bold;
          }
        }
        
        .user-name {
          font-size: 16px;
          font-weight: 500;
          color: #24292f;
        }
      }
    }
    
    .dialog-body {
      flex: 1;
      overflow-y: auto;
      padding: 20px;
      background: #fafbfc;
      
      .loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        
        svg {
          animation: spin 1s linear infinite;
          color: #667eea;
        }
      }
      
      .message-list {
        display: flex;
        flex-direction: column;
        gap: 16px;
        
        .message-item {
          display: flex;
          gap: 10px;
          
          &.received {
            justify-content: flex-start;
          }
          
          &.sent {
            justify-content: flex-end;
          }
          
          .message-avatar {
            width: 36px;
            height: 36px;
            flex-shrink: 0;
            
            img {
              width: 100%;
              height: 100%;
              border-radius: 50%;
              object-fit: cover;
            }
            
            .avatar-placeholder-tiny {
              width: 100%;
              height: 100%;
              border-radius: 50%;
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              color: white;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 14px;
              font-weight: bold;
            }
          }
          
          .message-bubble {
            max-width: 60%;
            
            .message-text {
              padding: 10px 14px;
              border-radius: 12px;
              font-size: 14px;
              line-height: 1.6;
              word-wrap: break-word;
            }
            
            .message-time {
              margin-top: 4px;
              font-size: 11px;
              color: #8c959f;
              padding: 0 4px;
            }
          }
          
          &.received .message-bubble {
            .message-text {
              background: white;
              color: #24292f;
              border: 1px solid #e1e4e8;
            }
            
            .message-time {
              text-align: left;
            }
          }
          
          &.sent .message-bubble {
            .message-text {
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              color: white;
            }
            
            .message-time {
              text-align: right;
            }
          }
        }
      }
    }
    
    .dialog-footer {
      border-top: 1px solid #eee;
      padding: 16px 20px;
      background: white;
      
      textarea {
        width: 100%;
        border: 1px solid #d0d7de;
        border-radius: 6px;
        padding: 10px 12px;
        font-size: 14px;
        resize: none;
        outline: none;
        transition: all 0.2s;
        font-family: inherit;
        
        &:focus {
          border-color: #667eea;
          box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        &::placeholder {
          color: #8c959f;
        }
      }
      
      .footer-actions {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 10px;
        
        .char-count {
          font-size: 12px;
          color: #8c959f;
        }
        
        .btn-send {
          padding: 8px 20px;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          border: none;
          border-radius: 6px;
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.2s;
          
          &:hover:not(:disabled) {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
          }
          
          &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
          }
        }
      }
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

